import datetime

import tornado.gen
import tornado.httpclient
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
from tornado.web import RequestHandler
from bot.enterprise_wechat_gpt.util.user_info_util import *
from bot.enterprise_wechat_gpt.util.constant.loan_url import *
from bot.enterprise_wechat_gpt.util.tair_util import tair_util
from bot.enterprise_wechat_gpt.util.constant.hidden_character import *


class ActiveSendHandler(RequestHandler):

    executor = ThreadPoolExecutor(8)

    @tornado.gen.coroutine
    def get(self):
        output = yield self.handle_get()
        self.write(json.dumps(output, ensure_ascii=False))

    @run_on_executor
    def handle_get(self):
        output = {
            'msgtype': 'text',
            'text': {
                'content': ''
            }
        }
        wx_id = self.get_argument("wxId")
        customer_id = self.get_argument("customerId")
        agent_name = self.get_argument("agentName")
        user_pool = self.get_argument("userPool", None)

        user_info = get_user_info_dict_redis(wx_id)
        msg = get_output(user_pool, agent_name, wx_id, output, user_info)

        logging.info(f"response_active?wxId={wx_id}&customerId={customer_id}&agentName={agent_name}&userPool={user_pool}"
                     f"\n output:{json.dumps(output, ensure_ascii=False)}")
        coupon = user_info.get("coupon")
        has_coupon = len(coupon) == 1
        tag = user_info.get("tag")
        remain_balance = tag.get("金条剩余额度_实时", None)
        val = (wx_id, customer_id, user_pool, has_coupon, remain_balance, msg, datetime.datetime.now())

        with postgre_sql.get_resource() as (cursor, conn):
            cursor.execute(f"insert into public.wechat_activate(wx_id, customer_id, user_pool, has_coupon, remain_balance, send_msg, send_time)"
                           f" values (%s, %s, %s ,%s, %s, %s, %s) "
                           , val)
            logging.info(f"插入群发记录信息成功 wx_id:{wx_id}")
        return output


coupon_map = {
    "11月8折息费折扣券": "8折息费折扣券",
    "贴息30天免息": "30天免息券（稀缺紧张）",
    "贴息6折息费折扣券": "6折息费折扣券",
}

send_coupon_success = """[username][性别]我这边手上还有最后一张8折息费券，先发到您账户，免得后面没有了\n
使用方法：点击👉【[跟单链接]】借款——“灵活还”，勾选优惠，就使用哦！（APP借款不是您专属链接，以后无法再给您申请优惠的）\n❗券3天内消失 ，不要浪费啦不补发哟"""


send_coupon_fail = """亲，在么？年底最后3天，您的金条借款专属福利：\n①专属【额度加油包】，为您提额！\n②抽奖活动资格，iPhone14、金条优惠券等，为您呈现！\n
点【http://3.cn/10dQU-fmh】参与借款才有机会使用福利哦~有问题，回复【1】叫小鑫！"""


def get_output(userPool, agent_name, wx_id, output, user_info):
    msg = ''
    cur_date = datetime.datetime.now().strftime("%m-%d")
    try:
        tag = user_info.get('tag')
        sex = tag.get('性别')
        username = user_info.get('username')
        activityName = get_activityName(user_info)

        sending_task = tair_util.get(f"QW:ActiveSendTask:{userPool}:{agent_name}:{cur_date}:Sending")
        if sending_task is not None:
            sending_task = json.loads(sending_task)
            msg = str(sending_task['msg'])
            # select_coupon = sending_task.get('select_coupon', None)
            # if select_coupon is not None and select_coupon and activityName is not None:
            #     if activityName in ['11月8折息费折扣券']:
            #         output['coupon_name'] = activityName
            #         output['send_coupon_fail_msg'] = send_coupon_fail
            #         logging.info(f"{userPool}:{agent_name}:{wx_id} coupon:{activityName} 触发发券动作")
            #         msg = send_coupon_success
            logging.info(f"[个性化话术] {userPool}:{agent_name}:{wx_id} 原始话术是:{msg}")
            msg = msg.replace("[称呼]", get_nickname_by_sex(sex))

            if sex not in ['男', '女']:
                logging.warning("[个性化话术] 该用户没有性别")
                msg = msg.replace("[username]", "")
                msg = msg.replace("[性别]", "")
            else:
                if username == "-****" or username is None or username == "":
                    msg = msg.replace("[username]", "")
                    msg = msg.replace("[性别]", get_nickname_by_sex(sex))
                else:
                    msg = msg.replace("[username]", username[0])
                    msg = msg.replace("[性别]", get_nickname_by_sex_(sex))
            if activityName is not None:
                activityName = get_new_coupon_name(activityName, wx_id)
                msg = msg.replace("[activityName]", activityName)
            # else:
            #     msg = f"[称呼]金条利率调整的名额给您占上了哈，点击【{get_url_by_user_pool(userPool)}】查看详情哈~有需要回【1】叫小鑫！"
            #     msg = msg.replace("[称呼]", get_nickname_by_sex(sex))
            msg = msg.replace("[跟单链接]", get_url_by_user_pool(userPool))
            msg += get_hidden_character(userPool)
            logging.info(f"[个性化话术] {userPool}:{agent_name}:{wx_id} 更改话术为:{msg}")
        else:
            logging.warning(f"[个性化话术] {userPool}:{agent_name}:{wx_id} 没有正在发送的任务！")
    except Exception as e:
        logging.error(f"[个性化话术] 获取个性化话术异常, 不更改原始话术 e:{traceback.format_exc()}")
        msg = ''
    output['text']['content'] = msg
    return msg


def get_activityName(user_info):
    coupon = user_info.get('coupon')
    if coupon:
        activityName = coupon[0].get('activityName')
    else:
        activityName = None
    return activityName


def get_new_coupon_name(activityName, wx_id):
    new_coupon_name = coupon_map.get(activityName, None)
    if new_coupon_name is not None:
        logging.info(f"{wx_id}【{activityName}】优惠券更改为新名字:【{new_coupon_name}】")
        activityName = new_coupon_name
    return activityName


def get_nickname_by_sex(sex):
    if sex == '男':
        return '小哥哥'
    elif sex == '女':
        return '小姐姐'
    else:
        logging.warning("[个性化话术] 该用户没有性别")
        return ''


def get_nickname_by_sex_(sex):
    if sex == '男':
        return '先生'
    elif sex == '女':
        return '女士'
    else:
        logging.warning("[个性化话术] 该用户没有性别")
        return ''
